from asyncio.log import logger
from random import randint

from home.models import *
from django.http import HttpResponseBadRequest, JsonResponse
from django.shortcuts import *

from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse

from django.views import View
from libs.captcha.captcha import captcha  # 导入图片验证库
from django_redis import get_redis_connection
from libs.yuntongxun.sms import CCP
from django.contrib.auth import *  # 导入django自带退出包

from utils.response_code import RETCODE
import json

# 注册
class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        # 1、接受用户数据
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        sms_code = request.POST.get('sms_code')
        # 2、验证数据
        # 2-1、参数是否齐全
        if not all([mobile, password, password2, sms_code]):
            return HttpResponseBadRequest('参数不全')
        # 2-2、手机号格式是否正确
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseBadRequest('手机号码格式不正确')
        # 2-3、密码是否符合格式
        if not re.match(r'^[0-9a-zA-Z]{8,20}$', password) or not re.match(r'^[0-9a-zA-Z]{8,20}$', password2):
            return HttpResponseBadRequest('密码长度、格式不正确。长度8-20，必须是数字、字母')
        # 2-4、密码和确认密码是否一致
        if password != password2:
            return HttpResponseBadRequest('两次输入的密码不一致')
        # 获取Redis中的短信验证码
        redis_coon = get_redis_connection()
        redis_sms_code = redis_coon.get('sms:%s' % mobile)
        if redis_sms_code.decode() != sms_code:
            return HttpResponseBadRequest('短信验证码错误')
        # 3、保存注册信息
        user = User.objects.create_user(username=mobile, mobile=mobile, password=password)

        login(request,user)
        resp = redirect(reverse('home:index'))
        resp.set_cookie('is_login',True)
        resp.set_cookie('login_name',user.username)
        return resp

# 图片验证码
class ImageView(View):
    def get(self, request):
        # 步骤：1、接收前端传递过来的uuid
        uuid = request.GET.get('uuid')
        # 2、判断uuid失分获取到
        if uuid is None:
            return HttpResponse('uuid不存在')
        # 3、通过调用captcha来生成图片验证码（返回：图片内容和图片二进制）
        txt, image = captcha.generate_captcha()  # 注册页面的路由
        # 4、将图片内容保存到redis中。uuid作为key，图片内容作为值，同时还需要设置一个过期时间
        redis_conn = get_redis_connection('default')
        # name:数据key，这里采用img前缀：uuid
        # time：300秒后过期
        # value：对应key的值
        redis_conn.setex(name='img:%s' % uuid, time=300, value=txt)
        # 5、返回图片给前端
        return HttpResponse(image, content_type='image/jpeg')
        pass

# 手机验证码
class SmsCodeView(View):
    def get(self, request):
        # 1、接收用户输入的参数
        mobile = request.GET.get('mobile')
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        # 2、参数校验
        # 2-1、验证参数是否安全
        if not all([mobile, image_code, uuid]):
            return JsonResponse({'code': RETCODE.NECESSARYPARAMERR, 'errmsg': '参数不全'})
        # 2-2、图片验证码的验证
        redis_conn = get_redis_connection()
        # 从Redis中获取已经存入的图片验证码信息
        image_code_redis = redis_conn.get('img:%s' % uuid)
        if image_code_redis is None:
            return JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图片验证码不正确'})
        # 删除radis中已经验证的图片验证码
        redis_conn.delete('img:%s' % uuid)
        # 判断图片验证码是否正确、Redis中取出的数据需要解码.decode（）
        if image_code.lower() != image_code_redis.decode().lower():
            return JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图片验证码错误'})
        # 3、生成短信验证码：生成6位数验证码
        sms_code = '%06d' % randint(0, 999999)
        ccp = CCP()
        ccp.send_template_sms('13992731623', [sms_code, 5], 1)
        print(f'你的验证码是：{sms_code}')
        # 4、保存短信验证码内容到redis中,保存时间1分钟
        redis_conn.setex('sms:%s' % mobile, 60, sms_code)
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '短信发送成功'})

# 登录
class LoginView(View):
    def get(self,request):
        return render(request,'login.html')

    def post(self,request):
        # 1、接收提交参数
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        remember = request.POST.get('remember')
        # 2、验证参数
        if not all([mobile,password]):
            return render(request,'login.html',{'msg':'参数不齐全'})
        # 2-1、手机号码是否符合规则
        if not re.match('^1[3-9]\d{9}$',mobile):
            return render(request,'login.html',{'msg':'手机号格式不正确'})
        # 2-2、密码是否符合规则
        if not re.match('^[a-z0-9A-Z]{8,20}$',password):
            return render(request,'login.html',{'msg':'密码格式不正确'})
        # 3、用户认证登录
        # 使用Django自带的用户认证代码，将会返回一个user对象，如果账号密码正确，那么就返回对象，否则返回None
        return_user = authenticate(mobile=mobile,password=password)
        if return_user is None:
            return render(request,'login.html',{'msg':'账号或密码错误'})
        # 4、状态保持
        login(request, return_user)

        # 5、根据用户选择的是否记住登录状态进行判断
        next_page = request.GET.get('next')
        if next_page:
            resp = redirect(next_page)
        else:
            resp = redirect(reverse('home:index'))

        if remember != 'on':  # 用户未勾选
            request.session.set_expiry(0)  # 当浏览器关闭后，清空session
            u = json.dumps(return_user.username)
            resp.set_cookie('is_login', True)
            resp.set_cookie('login_name', u)
        else:  # 用户勾选
            request.session.set_expiry(None)  # 设置session的过期时常时间为默认值，默认值时间为两周
            resp.set_cookie('is_login', True, max_age=14 * 24 * 3600)
            u = json.dumps(return_user.username)
            resp.set_cookie('login_name', u, max_age=14 * 24 * 3600)

        return resp

# 退出登录
class LogoutView(View):
    def get(self,request):
        # 1、清楚session数据
        logout(request)
        resp = redirect(reverse('home:index'))
        # 2、删除cookie数据
        resp.delete_cookie('is_login')
        resp.delete_cookie('login_name')
        # 3、跳转到首页
        return resp

# 忘记密码
class ForgetPasswordView(View):
    def get(self,request):
        return render(request,'forgetpassword.html')

    def post(self,request):
        # 1、接收数据
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        sms_code = request.POST.get('sms_code')
        # 2、验证数据
        # 2 - 1、判断参数是否齐全
        if not all([mobile,password,password2,sms_code]):
            return render(request,'forgetpassword.html',{'msg':'缺少必要的参数'})
        # 2 - 2、手机号是否符合规则
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return render(request, 'forgetpassword.html', {'msg': '手机号格式不正确'})
        # 2 - 3、判断密码是否符合规则
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return render(request, 'forgetpassword.html', {'msg': '密码格式不正确'})
        # 2 - 4、判断确认密码是否一致
        if password != password2:
            return render(request, 'forgetpassword.html', {'msg': '两次密码输入不一致'})

        redis_conn = get_redis_connection('default')
        sms_code_redis = redis_conn.get(f'sms:{mobile}')
        # 2 - 5、判断短信验证码是否正确
        if sms_code_redis is None:
            return render(request, 'forgetpassword.html', {'msg': '短信验证码过期'})
        if sms_code_redis.decode() != sms_code:
            return render(request, 'forgetpassword.html', {'msg': '短信验证码错误'})
        redis_conn.delete(f'sms:{mobile}')
        # 3、根据手机号码进行用户信息的查询
        userinfo = User.objects.get(mobile=mobile);
        userinfo.set_password(password)
        userinfo.save()
        # 6、进行页面跳转，跳转到登录页面
        resp = redirect(reverse('users:login'))
        # 7、返回响应
        return resp

# 用户中心
class UserCenter(LoginRequiredMixin,View):
    def get(self,request):
        # if not request.user.is_authenticated:
        #     return redirect(reverse('users:login'))
        userinfo = request.user  #获取已登录用户信息
        uu = {
            'mobile':userinfo.mobile,
            'username':userinfo.username,
            'avatar':userinfo.avatar.url if userinfo.avatar else None,
            'desc':userinfo.user_desc,
        }
        return render(request,'usercenter.html',context=uu)

    def post(self,request):
        username = request.POST.get('username')
        desc = request.POST.get('desc')
        avatar = request.FILES.get('avatar')

        userinfo = request.user  #获取到已经登录的用户信息，并且这个用户是被orm跟踪
        userinfo.username = username
        userinfo.user_desc = desc
        userinfo.avatar = avatar
        userinfo.save()

        resp = redirect(reverse('users:usercenter'))
        u = json.dumps(userinfo.username)
        resp.set_cookie('login_name',u)

        return resp

# 写文章
class WriteBlogView(View):
    def get(self,request):
        contxt = ArticleCategory.objects.all()
        return render(request,'writeblog.html', context={'list':contxt})

    def post(self,request):
        # 1、接收数据
        avatar = request.FILES.get('avatar')
        title = request.POST.get('title')
        category_id = request.POST.get('category')
        tags = request.POST.get('tags')
        sumary = request.POST.get('sumary')
        content = request.POST.get('content')
        user = request.user
        print([avatar, title, category_id, sumary, content])
        # 2、验证数据
        # 2-1、参数齐全验证
        if not all([avatar, title, category_id, sumary, content]):
            return HttpResponseBadRequest('参数不齐全')
        # 2-2、判断分类id
        try:
            category = ArticleCategory.objects.filter(pk=category_id).first()
        except ArticleCategory.DoesNotExist:
            return HttpResponseBadRequest('没有该分类信息')
        # 3、数据入库
        try:
            Article.objects.create(
                title=title,
                author=user,
                avatar=avatar,
                category=category,
                tags=tags,
                sumary=sumary,
                content=content
            )
        except Exception as e:
            logger.error(e)
            return HttpResponseBadRequest('发布失败，请稍后重试')
        # 4、跳转到指定页面
        return redirect(reverse('home:index'))


    




